<?php

namespace App\Store\Controllers\Financial\Statements;

use App\Admin\Models\SiteStore;
use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Financial\Statements\FinancialStatementsProfit;
use App\Store\Models\Financial\Statements\Liabilities;
use App\Store\Models\Financial\Statements\Moneylog;
use App\Store\Models\Financial\Statements\Subject;
use App\Store\Models\Financial\Statements\Voucher;
use App\Store\Models\Goods\GoodsStockin;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderDeposit;
use App\Store\Models\Order\OrderRecharge;
use Illuminate\Http\Request;
use App\Store\Validate\Financial\Statements\Liabilities as ValidateLiabilities;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class LiabilitiesController extends Controller
{


    public function getlist(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $req_data = $request->only(['store_id', 'date']);
        $date = $req_data['date'] ?? date('Y-m-d');

        $start_time = strtotime(date('Y', strtotime($date)) . '-01-01' . ' 00:00:00');
        $end_time = strtotime($req_data['date'] . ' 23:59:59');

        $finalwhere[] = ['store_id', '=', $req_data['store_id']];
        $finalwhere[] = ['voucher_date', '>=', $start_time];
        $finalwhere[] = ['voucher_date', '<=', $end_time];
        $finalwhere[] = ['cp_id', '=', $cp_id];

        $subjectList = Subject::query()
            ->where('is_del', 1)
            ->where(function ($query) use ($cp_id) {
                $query->where('cp_id', $cp_id)
                    ->orWhere('cp_id', 0);
            })
            ->whereNotNull('serial_number')
            ->get(['serial_number', 'upper_number'])
            ->toArray();

        $list = (new Voucher())->getVoucherList($finalwhere);
        $finalAsset = $this->getAssetCalculate($list, $subjectList);


        $final[] = ['store_id', '=', $req_data['store_id']];
        $final[] = ['date', '>=', date('Y-m', strtotime($date)) . '-01'];
        $final[] = ['date', '<=', $req_data['date']];
        $finalAmount51 = FinancialStatementsProfit::query()->where($final)->sum('data_key_32');




        // 获取上一年的日期
        $prev_year = date('Y', strtotime('-1 year', strtotime($date)));
        $prev_start_date = $prev_year . '-01-01';
        $prev_end_date = $prev_year . '-12-31';

        $prev_start_time = strtotime($prev_start_date . ' 00:00:00');
        $prev_end_time = strtotime($prev_end_date . ' 23:59:59');

        $beginwhere[] = ['store_id', '=', $req_data['store_id']];
        $beginwhere[] = ['voucher_date', '>=', $prev_start_time];
        $beginwhere[] = ['voucher_date', '<=', $prev_end_time];
        $beginwhere[] = ['cp_id', '=', $cp_id];


        $list1 = (new Voucher())->getVoucherList($beginwhere);

        $beginAsset = $this->getAssetCalculate($list1, $subjectList);

        $begin[] = ['store_id', '=', $req_data['store_id']];
        $begin[] = ['date', '>=', $prev_start_date];
        $begin[] = ['date', '<=', $prev_end_date];

        // 获取去年的利润
        $beginAmount51 = FinancialStatementsProfit::query()->where($begin)->sum('data_key_32');

        $amount51 = $beginAmount51 + $finalAmount51;

        $finalLiability = $this->getLiabilityCalculate($list, $subjectList, $amount51);

        $beginLiability = $this->getliabilityCalculate($list1, $subjectList, $beginAmount51);


        $data = [
            [
                'asset_row' => '',
                'asset_name' => '流动资产:',
                'asset_amount' => '',
                'asset_final_amount' => '',
                'asset_begin_amount' => '',


                'debt_row' => '',
                'debt_name' => '流动负债:',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',
            ],
            [
                'asset_row' => '1',
                'asset_name' => '货币资金',
                'asset_final_amount' => $finalAsset['amount1'] / 100,
                'asset_begin_amount' => $beginAsset['amount1'] / 100,

                'debt_row' => '31',
                'debt_name' => '短期借款',
                'debt_final_amount' => $finalLiability['amount31'] / 100,
                'debt_begin_amount' => $beginLiability['amount31'] / 100,
            ],
            [
                'asset_row' => '2',
                'asset_name' => '短期投资',
                'asset_final_amount' => $finalAsset['amount2'] / 100,
                'asset_begin_amount' => $beginAsset['amount2'] / 100,

                'debt_row' => '32',
                'debt_name' => '应付票据',
                'debt_final_amount' => $finalLiability['amount32'] / 100,
                'debt_begin_amount' => $beginLiability['amount32'] / 100,
            ],

            [
                'asset_row' => '3',
                'asset_name' => '应收票据',
                'asset_final_amount' => $finalAsset['amount3'] / 100,
                'asset_begin_amount' => $beginAsset['amount3'] / 100,

                'debt_row' => '33',
                'debt_name' => '应付账款',
                'debt_final_amount' => $finalLiability['amount33'] / 100,
                'debt_begin_amount' => $beginLiability['amount33'] / 100,
            ],
            [
                'asset_row' => '4',
                'asset_name' => '应收账款',
                'asset_final_amount' => $finalAsset['amount4'] / 100,
                'asset_begin_amount' => $beginAsset['amount4'] / 100,

                'debt_row' => '34',
                'debt_name' => '预收账款',
                'debt_final_amount' => $finalLiability['amount34'] / 100,
                'debt_begin_amount' => $beginLiability['amount34'] / 100,
            ],
            [
                'asset_row' => '5',
                'asset_name' => '预付账款',
                'asset_final_amount' => $finalAsset['amount5'] / 100,
                'asset_begin_amount' => $beginAsset['amount5'] / 100,


                'debt_row' => '35',
                'debt_name' => '应付职工薪酬',
                'debt_final_amount' => $finalLiability['amount35'] / 100,
                'debt_begin_amount' => $beginLiability['amount35'] / 100,
            ],
            [
                'asset_row' => '6',
                'asset_name' => '应收股利',
                'asset_final_amount' => $finalAsset['amount6'] / 100,
                'asset_begin_amount' => $beginAsset['amount6'] / 100,

                'debt_row' => '36',
                'debt_name' => '应交税费',
                'debt_final_amount' => $finalLiability['amount36'] / 100,
                'debt_begin_amount' => $beginLiability['amount36'] / 100,
            ],
            [
                'asset_row' => '7',
                'asset_name' => '应收利息',
                'asset_final_amount' => $finalAsset['amount7'] / 100,
                'asset_begin_amount' => $beginAsset['amount7'] / 100,

                'debt_row' => '37',
                'debt_name' => '应付利息',
                'debt_final_amount' => $finalLiability['amount37'] / 100,
                'debt_begin_amount' => $beginLiability['amount37'] / 100,
            ],
            [
                'asset_row' => '8',
                'asset_name' => '其他应收款',
                'asset_final_amount' => $finalAsset['amount8'] / 100,
                'asset_begin_amount' => $beginAsset['amount8'] / 100,

                'debt_row' => '38',
                'debt_name' => '应付利润',
                'debt_final_amount' => $finalLiability['amount38'] / 100,
                'debt_begin_amount' => $beginLiability['amount38'] / 100,
            ],

            [
                'asset_row' => '9',
                'asset_name' => '存货',
                'asset_final_amount' => $finalAsset['amount9'] / 100,
                'asset_begin_amount' => $beginAsset['amount9'] / 100,

                'debt_row' => '39',
                'debt_name' => '其他应付款',
                'debt_final_amount' => $finalLiability['amount39'] / 100,
                'debt_begin_amount' => $beginLiability['amount39'] / 100,
            ],
            [
                'asset_row' => '10',
                'asset_name' => '其中：原材料',
                'asset_final_amount' => $finalAsset['amount10'] / 100,
                'asset_begin_amount' => $beginAsset['amount10'] / 100,

                'debt_row' => '40',
                'debt_name' => '其他流动负债',
                'debt_final_amount' => $finalLiability['amount40'] / 100,
                'debt_begin_amount' => $beginLiability['amount40'] / 100,
            ],
            [
                'asset_row' => '11',
                'asset_name' => '在产品',
                'asset_final_amount' => $finalAsset['amount11'] / 100,
                'asset_begin_amount' => $beginAsset['amount11'] / 100,

                'debt_row' => '41',
                'debt_name' => '流动负债合计',
                'debt_final_amount' => $finalLiability['amount41'] / 100,
                'debt_begin_amount' => $beginLiability['amount41'] / 100,
            ],
            [
                'asset_row' => '12',
                'asset_name' => '库存商品',
                'asset_final_amount' => $finalAsset['amount12'] / 100,
                'asset_begin_amount' => $beginAsset['amount12'] / 100,

                'debt_row' => '',
                'debt_name' => '非流动负债:',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',
            ],
            [
                'asset_row' => '13',
                'asset_name' => '周转材料',
                'asset_final_amount' => $finalAsset['amount13'] / 100,
                'asset_begin_amount' => $beginAsset['amount13'] / 100,

                'debt_row' => '42',
                'debt_name' => '长期借款',
                'debt_final_amount' => $finalLiability['amount42'] / 100,
                'debt_begin_amount' => $beginLiability['amount42'] / 100,
            ],
            [
                'asset_row' => '14',
                'asset_name' => '其他流动资产',
                'asset_final_amount' => $finalAsset['amount14'] / 100,
                'asset_begin_amount' => $beginAsset['amount14'] / 100,

                'debt_row' => '43',
                'debt_name' => '长期应付款',
                'debt_final_amount' => $finalLiability['amount43'] / 100,
                'debt_begin_amount' => $beginLiability['amount43'] / 100,
            ],
            [
                'asset_row' => '15',
                'asset_name' => '流动资产合计',
                'asset_final_amount' => $finalAsset['amount15'] / 100,
                'asset_begin_amount' => $beginAsset['amount15'] / 100,

                'debt_row' => '44',
                'debt_name' => '递延收益',
                'debt_final_amount' => $finalLiability['amount44'] / 100,
                'debt_begin_amount' => $beginLiability['amount44'] / 100,
            ],
            [
                'asset_row' => '',
                'asset_name' => '非流动资产:',
                'asset_final_amount' => '',
                'asset_begin_amount' => '',


                'debt_row' => '45',
                'debt_name' => '其他非流动负债',
                'debt_final_amount' => $finalLiability['amount45'] / 100,
                'debt_begin_amount' => $beginLiability['amount45'] / 100,
            ],
            [
                'asset_row' => '16',
                'asset_name' => '长期债券投资',
                'asset_final_amount' => $finalAsset['amount16'] / 100,
                'asset_begin_amount' => $beginAsset['amount16'] / 100,

                'debt_row' => '46',
                'debt_name' => '非流动负债合计',
                'debt_final_amount' => $finalLiability['amount46'] / 100,
                'debt_begin_amount' => $beginLiability['amount46'] / 100,
            ],
            [
                'asset_row' => '17',
                'asset_name' => '长期股权投资',
                'asset_final_amount' => $finalAsset['amount17'] / 100,
                'asset_begin_amount' => $beginAsset['amount17'] / 100,

                'debt_row' => '47',
                'debt_name' => '负债合计',
                'debt_final_amount' => $finalLiability['amount47'] / 100,
                'debt_begin_amount' => $beginLiability['amount47'] / 100,
            ],
            [
                'asset_row' => '18',
                'asset_name' => '固定资产原价',
                'asset_final_amount' => $finalAsset['amount18'] / 100,
                'asset_begin_amount' => $beginAsset['amount18'] / 100,

                'debt_row' => '',
                'debt_name' => '',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',

            ],
            [
                'asset_row' => '19',
                'asset_name' => '减：累计折旧',
                'asset_final_amount' => $finalAsset['amount19'] / 100,
                'asset_begin_amount' => $beginAsset['amount19'] / 100,

                'debt_row' => '',
                'debt_name' => '',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',

            ],
            [
                'asset_row' => '20',
                'asset_name' => '固定资产账面价值',
                'asset_final_amount' => $finalAsset['amount20'] / 100,
                'asset_begin_amount' => $beginAsset['amount20'] / 100,

                'debt_row' => '',
                'debt_name' => '',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',

            ],
            [
                'asset_row' => '21',
                'asset_name' => '在建工程',
                'asset_final_amount' => $finalAsset['amount21'] / 100,
                'asset_begin_amount' => $beginAsset['amount21'] / 100,

                'debt_row' => '',
                'debt_name' => '',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',
            ],
            [
                'asset_row' => '22',
                'asset_name' => '工程物资',
                'asset_final_amount' => $finalAsset['amount22'] / 100,
                'asset_begin_amount' => $beginAsset['amount22'] / 100,

                'debt_row' => '',
                'debt_name' => '',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',

            ],
            [
                'asset_row' => '23',
                'asset_name' => '固定资产清理',
                'asset_final_amount' => $finalAsset['amount23'] / 100,
                'asset_begin_amount' => $beginAsset['amount23'] / 100,

                'debt_row' => '',
                'debt_name' => '',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',

            ],
            [
                'asset_row' => '24',
                'asset_name' => '生产性生物资产',
                'asset_final_amount' => $finalAsset['amount24'] / 100,
                'asset_begin_amount' => $beginAsset['amount24'] / 100,

                'debt_row' => '',
                'debt_name' => '所有者权益（或股东权益）',
                'debt_final_amount' => '',
                'debt_begin_amount' => '',

            ],
            [
                'asset_row' => '25',
                'asset_name' => '无形资产',
                'asset_final_amount' => $finalAsset['amount25'] / 100,
                'asset_begin_amount' => $beginAsset['amount25'] / 100,

                'debt_row' => '48',
                'debt_name' => '实收资本（或股本）',
                'debt_final_amount' => $finalLiability['amount48'] / 100,
                'debt_begin_amount' => $beginLiability['amount48'] / 100,
            ],
            [
                'asset_row' => '26',
                'asset_name' => '开发支出',
                'asset_final_amount' => $finalAsset['amount26'] / 100,
                'asset_begin_amount' => $beginAsset['amount26'] / 100,

                'debt_row' => '49',
                'debt_name' => '资本公积',
                'debt_final_amount' => $finalLiability['amount49'] / 100,
                'debt_begin_amount' => $beginLiability['amount49'] / 100,
            ],
            [
                'asset_row' => '27',
                'asset_name' => '长期待摊费用',
                'asset_final_amount' => $finalAsset['amount27'] / 100,
                'asset_begin_amount' => $beginAsset['amount27'] / 100,

                'debt_row' => '50',
                'debt_name' => '盈余公积',
                'debt_final_amount' => $finalLiability['amount50'] / 100,
                'debt_begin_amount' => $beginLiability['amount50'] / 100,
            ],
            [
                'asset_row' => '28',
                'asset_name' => '其他非流动资产',
                'asset_final_amount' => $finalAsset['amount28'] / 100,
                'asset_begin_amount' => $beginAsset['amount28'] / 100,

                'debt_row' => '51',
                'debt_name' => '未分配利润',
                'debt_final_amount' => $finalLiability['amount51'] / 100,
                'debt_begin_amount' => $beginLiability['amount51'] / 100,
            ],
            [
                'asset_row' => '29',
                'asset_name' => '非流动资产合计',
                'asset_final_amount' => $finalAsset['amount29'] / 100,
                'asset_begin_amount' => $beginAsset['amount29'] / 100,

                'debt_row' => '52',
                'debt_name' => '所有者权益（或股东权益）合计',
                'debt_final_amount' => $finalLiability['amount52'] / 100,
                'debt_begin_amount' => $beginLiability['amount52'] / 100,
            ],
            [
                'asset_row' => '30',
                'asset_name' => '资产总计',
                'asset_final_amount' => $finalAsset['amount30'] / 100,
                'asset_begin_amount' => $beginAsset['amount30'] / 100,

                'debt_row' => '53',
                'debt_name' => '负债和所有者权益（或股东权益）总计',
                'debt_final_amount' => $finalLiability['amount53'] / 100,
                'debt_begin_amount' => $beginLiability['amount53'] / 100,
            ],

        ];

        $isExport = $request->isExport ?? 0;

        if ($isExport == 1) {

            return $data;
        } else {
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
        }

    }

    public function getone(Request $request)
    {
        $data = $this->getdata($request);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $data]);
    }

    public function doexport(Request $request)
    {
        $req_data = $request->only(['store_id', 'date']);
        if (!isset($req_data['store_id'])) {
            return response()->json(['code' => '001', 'msg' => '请先选择门店']);
        }

        $request->isExport = 1;
        $exceldata = $this->getlist($request);
        $store_name = SiteStore::where('id', '=', $req_data['store_id'])->value('store_name');
        $row = [
            ['资产负债表'],
            [$store_name . ' ' . $req_data['date']],
            [

                'asset_name' => '资产',
                'asset_row' => '行次',
                'asset_final_amount' => '期末金额（公式）（当前1月1日至报表日期）',
                'asset_begin_amount' => '期末金额（公式）（当前1月1日至报表日期',

                'debt_name' => '负债和所有者权益',
                'debt_row' => '行次',
                'debt_final_amount' => '期末金额（公式）',
                'debt_begin_amount' => '年初金额（公式）',
            ],
        ];

        $datawith = [
            'A' => '30', 'B' => '5', 'C' => '50', 'D' => '50', 'E' => '40', 'F' => '5', 'G' => '20', 'H' => '20'
        ];

        $filename = '资产负债表导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }


    public function getAssetCalculate($list, $subjectList)
    {
        $subject = new Subject();

        // 定义科目映射配置
        $subjectConfig = [
            'amount1' => ['1001', '1002', '1003', '1004', '1005'], // 货币资金
            'amount2' => ['1101'], // 短期投资
            'amount3' => ['1121'], // 应收票据
            'amount4' => ['1122'], // 应收账款
            'amount5' => ['1123'], // 预付账款
            'amount6' => ['1131'], // 应收股利
            'amount7' => ['1132'], // 应收利息
            'amount8' => ['1221'], // 其他应收款
            'amount10' => ['1401'], // 原材料
            'amount11' => ['1402'], // 在产品
            'amount12' => ['1405', '1406', '1407'], // 库存商品
            'amount13' => ['1408'], // 周转材料
            'amount14' => ['1463'], // 其他流动资产
            'amount16' => ['1521'], // 长期债券投资
            'amount17' => ['1511'], // 长期股权投资
            'amount18' => ['1601'], // 固定资产
            'amount19' => ['1602'], // 累计折旧
            'gdzcjzzb' => ['1603'], // 固定资产减值准备
            'amount21' => ['1604'], // 在建工程
            'amount22' => ['1605'], // 工程物资
            'amount23' => ['1606'], // 固定资产清理
            'amount24' => ['1621'], // 生产性生物资产
            'amount25' => ['1701', '1702', '1703'], // 无形资产
            'amount26' => ['4403'], // 开发支出
            'amount27' => ['1801'], // 长期待摊费用
            'amount28' => ['1811', '1821', '1901'], // 其他非流动资产
        ];

        // 初始化金额数组
        $debitAmounts = [];
        $creditAmounts = [];
        $codes = [];

        foreach ($subjectConfig as $key => $subjectNumbers) {
            $debitAmounts[$key] = 0;
            $creditAmounts[$key] = 0;
            $codes[$key] = $subject->getSubjectNumbers($subjectList, $subjectNumbers);
        }

        // 计算各科目金额
        foreach ($list as $item) {
            foreach ($codes as $key => $codeList) {
                if (in_array($item['serial_number'], $codeList)) {
                    $debitAmounts[$key] += $item['debit_amount'];
                    $creditAmounts[$key] += $item['credit_amount'];
                }
            }
        }

        // 计算净额
        $amounts = [];
        foreach ($debitAmounts as $key => $debitAmount) {
            $amounts[$key] = $debitAmount - $creditAmounts[$key];
        }

        // 特殊处理科目
        $amounts['amount19'] = $creditAmounts['amount19'] - $debitAmounts['amount19']; // 累计折旧
        $amounts['amount23']= $creditAmounts['amount23'] - $debitAmounts['amount23'];

        $gdzcjzzbAmount = $creditAmounts['gdzcjzzb'] - $debitAmounts['gdzcjzzb']; // 固定资产减值准备

        // 计算存货: 9 = 10 + 11 + 12 + 13
        $amounts['amount9'] = $amounts['amount10'] + $amounts['amount11'] + $amounts['amount12'] + $amounts['amount13'];

        // 计算流动资产合计: 15 = 1+2+3+4+5+6+7+8+9+14
        $amounts['amount15'] = $amounts['amount1'] + $amounts['amount2'] + $amounts['amount3'] +
            $amounts['amount4'] + $amounts['amount5'] + $amounts['amount6'] +
            $amounts['amount7'] + $amounts['amount8'] + $amounts['amount9'] +
            $amounts['amount14'];

        // 计算固定资产净值: 20 = 18 - 19 - 固定资产减值准备
        $amounts['amount20'] = $amounts['amount18'] - $amounts['amount19'] - $gdzcjzzbAmount;

        // 计算非流动资产合计: 29 = 16+17+20+21+22-23+24+25+26+27+28
        $amounts['amount29'] = $amounts['amount16'] + $amounts['amount17'] + $amounts['amount20'] +
            $amounts['amount21'] + $amounts['amount22'] -  $amounts['amount23'] +
            $amounts['amount24'] + $amounts['amount25'] + $amounts['amount26'] +
            $amounts['amount27'] + $amounts['amount28'];

        // 资产总计
        $amounts['amount30'] = $amounts['amount15'] + $amounts['amount29'];

        // 重命名键以保持与原始代码一致
        $result = [];
        foreach ($amounts as $key => $value) {
            if ($key !== 'gdzcjzzb') {
                $result[$key] = $value;
            }
        }

        return $result;
    }


    public function getLiabilityCalculate($list, $subjectList, $amount51 = 0)
    {
        // 定义科目配置映射
        $subjectConfigs = [
            '31' => ['codes' => ['2001'], 'name' => '短期借款'],
            '32' => ['codes' => ['2201'], 'name' => '应付票据'],
            '33' => ['codes' => ['2202'], 'name' => '应付账款'],
            '34' => ['codes' => ['2203'], 'name' => '预收账款'],
            '35' => ['codes' => ['2211'], 'name' => '应付职工薪酬'],
            '36' => ['codes' => ['2221'], 'name' => '应交税费'],
            '37' => ['codes' => ['2231'], 'name' => '应付利息'],
            '38' => ['codes' => ['2232'], 'name' => '应付利润'],
            '39' => ['codes' => ['2241'], 'name' => '其他应付款'],
            '40' => ['codes' => ['2404'], 'name' => '其他流动负债'],
            '42' => ['codes' => ['2501'], 'name' => '长期借款'],
            '43' => ['codes' => ['2801'], 'name' => '长期应付款'],
            '44' => ['codes' => ['2401'], 'name' => '递延收益'],
            '45' => ['codes' => ['2403'], 'name' => '其他非流动负债'],
            '48' => ['codes' => ['4001'], 'name' => '实收资本'],
            '49' => ['codes' => ['4002'], 'name' => '资本公积'],
            '50' => ['codes' => ['4101'], 'name' => '盈余公积']
        ];

        $subject = new  Subject();
        $amounts = [];
        $debitAmounts = [];
        $creditAmounts = [];

        // 初始化所有金额变量
        foreach (array_keys($subjectConfigs) as $key) {
            $debitAmounts[$key] = 0;
            $creditAmounts[$key] = 0;
            $amounts[$key] = 0;
        }

        // 预先获取所有科目代码
        $allCodes = [];
        foreach ($subjectConfigs as $key => $config) {
            $codes = $subject->getSubjectNumbers($subjectList, $config['codes']);
            $subjectConfigs[$key]['actual_codes'] = $codes;
            $allCodes = array_merge($allCodes, $codes);
        }

        // 构建科目代码到配置键的映射，提高查找效率
        $codeToKeyMap = [];
        foreach ($subjectConfigs as $key => $config) {
            foreach ($config['actual_codes'] as $code) {
                $codeToKeyMap[$code][] = $key;
            }
        }

        // 单次遍历处理所有数据
        foreach ($list as $item) {
            $serialNumber = $item['serial_number'];

            if (isset($codeToKeyMap[$serialNumber])) {
                foreach ($codeToKeyMap[$serialNumber] as $key) {
                    $debitAmounts[$key] += $item['debit_amount'];
                    $creditAmounts[$key] += $item['credit_amount'];
                }
            }
        }

        // 计算各科目金额
        foreach ($subjectConfigs as $key => $config) {
            $amounts[$key] = $creditAmounts[$key] - $debitAmounts[$key];
        }

        // 计算合计值
        // 流动负债合计 (31-40)
        $amount41 = $amounts['31'] + $amounts['32'] + $amounts['33'] + $amounts['34'] +
            $amounts['35'] + $amounts['36'] + $amounts['37'] + $amounts['38'] +
            $amounts['39'] + $amounts['40'];

        // 非流动负债合计 (42-45)
        $amount46 = $amounts['42'] + $amounts['43'] + $amounts['44'] + $amounts['45'];

        // 负债合计
        $amount47 = $amount41 + $amount46;

        // 所有者权益合计 (48-50 + 51)
        $amount52 = $amounts['48'] + $amounts['49'] + $amounts['50'] + $amount51;

        // 负债和所有者权益总计
        $amount53 = $amount47 + $amount52;

        // 构建返回结果
        $result = [];
        foreach ($subjectConfigs as $key => $config) {
            $result["amount{$key}"] = $amounts[$key];
        }

        // 添加计算出的合计值
        $result['amount41'] = $amount41;
        $result['amount46'] = $amount46;
        $result['amount47'] = $amount47;
        $result['amount51'] = $amount51;
        $result['amount52'] = $amount52;
        $result['amount53'] = $amount53;

        return $result;
    }

}
